import java.util.Stack;

/**
 * 227. 基本计算器 II
 * https://leetcode.cn/problems/basic-calculator-ii/description/
 */
class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack();
        char op = '+';

        int i = 0;
        while(i < s.length()) {
            char ch = s.charAt(i);
            if(ch == '+' || ch == '-' || ch == '*' || ch == '/') {
                //遇到符号
                op = ch;
            } else if(ch == ' ') {

            } else {
                //遇到数字
                int tmp = ch - '0';
                while((i + 1) < s.length() && s.charAt(i + 1) != '+'
                        && s.charAt(i + 1) != '-' && s.charAt(i + 1) != '*'
                        && s.charAt(i + 1) != '/' && s.charAt(i + 1) != ' ') {
                    tmp *= 10;
                    tmp += s.charAt(i + 1) - '0';
                    i++;
                }
                //把数字提取出来，分情况讨论
                if(op == '+') {
                    stack.add(tmp);
                } else if(op == '-') {
                    stack.push(-tmp);
                } else if(op == '*') {
                    stack.push(stack.pop() * tmp);
                } else {
                    stack.push(stack.pop() / tmp);
                }
            }
            i++;
        }

        //将栈中元素全部出栈相加
        int ret = 0;
        while(!stack.empty()) {
            ret += stack.pop();
        }

        return ret;
    }
}